package com.template.app.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.springframework.dao.support.DataAccessUtils;

import com.template.app.dao.Dao;
import com.template.app.support.DaoSupport;

public class DaoImpl<T> extends DaoSupport implements Dao<T> {
	
	private Class<T> type;
	
	@SuppressWarnings("unchecked")
	public DaoImpl() {
        ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
        type = (Class<T>) pt.getActualTypeArguments()[0];
    }
	
	public void save(T entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}
	
	public T get(Serializable id) {
		return getHibernateTemplate().get(type, id);
	}
	
	public void delete(T entity) {
		getHibernateTemplate().delete(entity);
	}
	
	protected T get(Serializable id, String queryName) {
		@SuppressWarnings("unchecked")
		List<T> result = getHibernateTemplate().findByNamedQueryAndNamedParam(queryName, "id", id);
		
		return DataAccessUtils.uniqueResult(result);
	}

}
